package com.example.DBUtil;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBConnection {

    private static final Logger logger = LoggerFactory.getLogger(DBConnection.class);



    public static Connection getConnection(String driver,String url,String user,String password){
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            return conn;
        } catch (Exception e) {
            logger.error("数据库连接失败，原因是" + e.getMessage());
            return conn;
        }
    }


    public static Map<String, Object> getResultMap(ResultSet rs) throws SQLException {
        Map<String, Object> hm = new HashMap<>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();// 获取列的数量
        for (int i = 1; i <= count; i++) {
            String key = rsmd.getColumnLabel(i);
            Object value = rs.getString(i);
            hm.put(key, value);
        }
        return hm;
    }


    private static List<Map> convertList(ResultSet rs) throws SQLException{
        List<Map> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取列的数量
        while (rs.next()) {
            Map<String,Object> rowData = new HashMap<>();//声明Map
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(rowData);
        }
        return list;
    }

}
